package com.csj.mvvm.utils

import android.os.Build
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.csj.mvvm.App
import com.csj.mvvm.R


object ToastUtil {

    fun showToast(message: String?) {
        showToast(message, false, Gravity.CENTER)
    }

    fun showToast(message: String?, isLong: Boolean) {
        showToast(message, isLong, Gravity.CENTER)
    }

    /**
     * gravity != -1 不自定义位置
     */
    fun showToast(message: String?, isLong: Boolean, gravity: Int) {
        if (!message.isNullOrEmpty()) {
            Toast.makeText(
                App.instance,
                null,
                if (isLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT
            ).apply {
                setView(getTextToastView(message))
                if (gravity != -1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.R)
                    setGravity(gravity, 0, 0)
                show()
            }
        }
    }

    private fun getTextToastView(text: CharSequence): View? {
        val vb : ViewDataBinding = DataBindingUtil.inflate(
            LayoutInflater.from(App.instance),
            R.layout.lay_toast,
            null,
            false
        )
        val mView = vb.root
//        val mView = LayoutInflater.from(App.instance).inflate(R.layout.lay_toast, null)
        (mView.findViewById(R.id.message) as TextView).text = text
        return mView
    }
}